package com.smarthealthring.mm.wxapi;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.smarthealthring.mm.App;
import com.smarthealthring.mm.api.ApiRequest;
import com.smarthealthring.mm.bean.WechatLoginRes;
import com.smarthealthring.mm.event.WechatLoginEvent;
import com.smarthealthring.mm.utils.ErrorHanding;
import com.smarthealthring.mm.utils.RandomUtil;
import com.smarthealthring.mm.utils.RxBus;
import com.smarthealthring.mm.utils.SPUtils;
import com.smarthealthring.mm.utils.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import java.util.HashMap;

import io.reactivex.functions.Consumer;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;
    private static final String TAG = WXEntryActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 注册微信sdk
        try {
            boolean result = (App.getInstance()).mWXAPI.handleIntent(getIntent(), this);
            if (!result) {
                Log.d("wx", "参数不合法，未被SDK处理，退出");
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onReq(BaseReq req) {
    }

    // 第三方发送到微信的请求处理后的响应结果，会回调该函数
    @Override
    public void onResp(BaseResp resp) {
        Logger.d(resp.errStr + ",errorCode = " + resp.errCode);

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                //拿到了微信返回的code,立马再去请求access_token
                String code = ((SendAuth.Resp) resp).code;
                Logger.d("code====" + code);
                SPUtils.setString("wxcode", code);

                RxBus.getInstance().send(new WechatLoginEvent(code));
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if (RETURN_MSG_TYPE_SHARE == resp.getType())
                    ToastUtil.shortShow("分享取消");
                else {
                    ToastUtil.shortShow("登录取消");
                }
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                if (RETURN_MSG_TYPE_SHARE == resp.getType())
                    ToastUtil.shortShow("分享被拒绝");
                else {
                    ToastUtil.shortShow("登录被拒绝");
                }
                finish();
                break;
        }
    }
}
